Model and subsystem function signatures

ABSTRACT

A system and method are provided to enable a user to specify function signatures for automated code generators to generate code based on a model representation. The method for automatically generating a function based on the model representation includes providing at least a portion of the model representation. A function signature is received for the model representation. The function signature is generated by a user. The function is generated based on the model representation and the function signature. A user interface can be provided to enable the user to enter the function signature and also to present a preview of a function that results from the function signature as modifications are made to the function signature. The user can enter the function signature using regular expressions, if desired.

FIELD OF THE INVENTION

The present invention relates to automated code generators fortransforming hierarchical block diagrams, or other graphical orotherwise hierarchical modeling structures, into software code, and moreparticularly to a system and method for specifying the functionsignature of an automatically generated function, and providing apreview of the automatically generated function.

BACKGROUND OF THE INVENTION

Dynamic systems are typically modeled in simulation environments as setsof differential, difference, and/or algebraic equations. At any giveninstant of time, these equations may be viewed as relationships betweenthe system's output response (“outputs”), the system's input stimuli(“inputs”) at that time, the current state of the system, the systemparameters, and time. The state of the system may be thought of as anumerical representation of the dynamically changing configuration ofthe system. For instance, in a physical system modeling a simplependulum, the state may be viewed as the current position and velocityof the pendulum. Similarly, a signal-processing system that filters asignal would maintain a set of previous inputs as the state. The systemparameters are the numerical representation of the static (unchanging)configuration of the system and may be viewed as constant coefficientsin the system's equations. For the pendulum example, a parameter is thelength of pendulum and for the filter example; a parameter is the valuesof the filter taps.

There are four common types of mathematical models used in the study ofdynamic systems. The first type of mathematical model describes systemsusing ordinary differential equations (ODEs) and is depicted in FIG. 1A.The dynamic system 2 specifies a set of two equations: Output 4 andDerivative 6. The Output equation 4 facilitates the computation of thesystem's output response at a given time instant as a function of itsinputs, states, parameters, and time. The Derivative equation 6 is anordinary differential equation that allows the computation of thederivative of the states at the current time as a function of theinputs, the states, parameters, and time. This class of models issuitable for systems in which it is important to track the systemresponse as a continuous function of time. Such continuous-time systemsare commonly representative of physical systems (mechanical, thermal,electrical). For simple systems, it may be possible to use the Output 4and Derivative equations 6 to obtain a closed-form solution for theoutput response y(t). But in most complex real world systems, theresponse of the system is obtained by integrating the states throughnumerical means.

The definition of an ODE used herein encompasses both implicit andexplicit differential equations. The class of ordinary differentialequations may require additional equations to define the system beingmodeled. For example, equations called projections may be required toimpose constraints on the differential variables (e.g., states X₁ and X₂must fall on the manifold defined by x₁ ²+x₂ ²=25). These constraintscan be either applied as a secondary condition or a coupled condition tothe differential equation. Although systems including the projectionsmay conventionally no longer qualify as an ODE; they are included hereto simplify the categories of systems. Another example is the use of aJacobian equation that defines partial derivatives with respect to theindependent and/or differential variables. The Jacobian equation istypically used when obtaining a linear approximation of a non-linearmodel or an overall linear model of a set of equations. Jacobianequations are required for some forms of numerical integration, forproducing the linear model once the model has reached its steady stateoperating point, etc. The Output 4 and Derivatives equations 6 may beextended to define other relationships for the block. For example, theOutput equation 4 may help manage its states by defining a relationshipwhere it resets the state back to a known quantity at a specific pointin time or when a specific condition is seen.

Another type of mathematical model describes systems using differenceequations as depicted in FIG. 1B. The dynamic system 8 specifies a setof two equations: Output 10 and Update 12. The Output equation 10facilitates the computation of the system's output response at a giventime instant as a function of the inputs, states at some previous time,parameters, and time. The Update equation 12 is a difference equationthat allows the computation of the states at the current time as afunction of the inputs, states at some previous time, parameters, andtime. This class of models is suitable for systems in which it isimportant to track the system response at discrete points in time. Suchdiscrete-time systems are commonly representative of discrete-timecontrol and digital signal processing systems. For simple systems, itmay be possible to use the Output 10 and Update equations 12 to obtain aclosed-form solution for the output response y(t). But in most complexreal world systems, the response of the system is solved throughrecursion. The Output 10 and Update equations 12 are applied repeatedlyto solve for the system response over a period of time.

An additional type of mathematical model describes systems usingalgebraic equations as depicted in FIG. 1C. The dynamic system 14 usesan algebraic equation 16 that needs to be solved at each time to obtainthe outputs. While simple systems may allow one to obtain a closed-formsolution for the system inputs and outputs, practical algebraicequations may best be solved iteratively using a numerical methodinvolving both perturbations and iterations. Algebraic equation solvingtechniques used in the context of dynamic system modeling are discussedin greater detail below.

A fourth type of mathematical model is a composite system that hascomponents that fall into the three types of models discussed above.Most complex real-world system models fall into this category. Thisclass of systems has Output, Derivative, Update, and potentially otherequations. Solving for the output response of such systems requires acombination of the solution approaches discussed for all of the classesabove. One example of a composite system is one described bydifferential-algebraic equations (DAEs) which contain both differentialequations and algebraic equations. Grouped within the composite class ofsystems are many extensions involving relationships (equations) definedin terms of both outputs and state. For example, one can define alimited integration relationship for a differential variable. Thisrelationship requires a set of equations that includes the Outputequation, an Update equation, a Derivative equation, and a Zero-crossingequation. The Zero-crossing equation defines the points in time wherethe upper and lower limits of the limited integration occur. Anotherexample of an extension is the notion of Enable and Disable equationsthat define relationships among states or signals when parts of a systemare activated and deactivated during execution.

Inherent in the four classes of systems (ODE, difference equations,algebraic equations and composite) is the notion of system sample time.The sample time is the time interval at which the inputs, state, oroutputs (collectively referred to as the results) of the system aretraced as time progresses. Based on sample times, a system can bedescribed as a discrete-time system, continuous-time system and hybridsystem. A discrete-time system is a system in which the evolution of thesystem results are tracked at finite intervals of time. In the limit asthe interval approaches zero, the discrete-time system becomes acontinuous-time system. The intervals of time may be periodic ornon-periodic. Sometimes, non-periodic rate systems are referred to asnon-uniform rate systems meaning that there is no periodic rate at whichthe response can be tracked. Non-uniform-rate systems can fall into theclass of composite systems where an additional equation(GetTimeOfNextVarHit) defines when in the future the other equationsassociated with the system should be evaluated. A continuous-time systemis a system in which the evolutions of the system results arecontinuously changing. Continuous-time signals change during numericalintegration (minor time steps). An example of a continuous-time systemis one described by an ODE. There can also be algebraic or compositecontinuous-time systems. A hybrid system is a system with bothdiscrete-time and continuous-time elements.

If a system has only one sample time, it is said to be single-rate. If asystem has multiple sample times, it is said to be multi-rate.Multi-rate systems can be evaluated (executed) using either asingle-tasking form of execution or a multi-tasking form of execution.When multi-tasking execution is used, it conforms to rate monotonicscheduling principals as defined by LIU, C. L., and LAYLAND, J. W.Scheduling Algorithms for Multiprogramming in a Hard-Real-TimeEnvironment. ACM 20, 1 (January 1973), 46-61. Systems may also becategorized by the type of numerical integration solver being used. Afixed-step system is one that uses a fixed-step solver. Fixed-stepsolvers typically use explicit methods to compute the next continuousstate at fixed periodic intervals of time. A variable-step system is onethat is using a variable-step solver. A variable-step solver can useeither implicit or explicit methods to compute the next continuous stateat non-periodic intervals of time. Generally, variable-step solvers usea form of error control to adjust the interval size such that thedesired error tolerances are achieved.

In practice, except for the most basic systems, mathematical models fordynamic systems involve a complex set of mathematical transformationsapplied in some prescribed manner with the outputs of sometransformations forming the inputs of others. Each elementaltransformation may be viewed in isolation as a simple dynamic systemfalling into one of the categories listed above. Therefore, a complexdynamic system may be modeled as an interconnection of various simpledynamic systems. A schematic representation of such an interconnectionthat has evolved over the years is the block diagram. Such block diagrammodels have now become a standard means in textbooks, design papers,journal articles, and specifications to communicate the details of adynamic system's behavior.

A block diagram model of a dynamic system is represented schematicallyas a collection of blocks interconnected by lines that representsignals. A signal represents the input and output of a dynamic system.Each block represents an elemental dynamic system. A line emanating atone block and terminating at another signifies that the output of thefirst block is an input to the second block. Each distinct input oroutput on a block is referred to as a port. Signals correspond to thetime-varying quantities represented by each line connection and areassumed to have values at each time instant. The source block of asignal writes to the signal at a given time instant when its systemequations are solved. The destination blocks of this signal read fromthe signal when their system equations are being solved. The basiccomponents of a block diagram are illustrated in FIG. 2. The blockdiagram includes a plurality of blocks 20, lines 22 and ports 24 thatare interconnected. Those skilled in the art will recognize that theterm “blocks” does not refer exclusively to elemental dynamic systemsbut may also include other modeling elements that aid in readability andmodularity of block diagrams.

The theory of Digital Signal Processing (DSP) focuses on modelingsignals as sequences of samples. This view naturally fits into thetime-based block diagram paradigm by mapping the samples u[n] todiscrete-time points u(t_(k)). This adds the benefit of being able tomodel the interaction between DSP systems and other classes oftime-based systems, e.g. continuous and/or discrete-time controlsystems.

Put another way, block diagram models are time-based relationshipsbetween signals and state variables representative of a dynamic system.The solution (computation of system response) of the model is obtainedby evaluating these relationships over time, where time starts at auser-specified “start time” and ends at a user-specified “stop time”.Each evaluation of these relationships is referred to as a time step.Signals represent quantities that change over time, and these quantitiesare defined for all points in time between the block diagram's start andstop time. The relationships between signals and state variables aredefined by sets of equations represented by blocks. These equationsdefine a relationship between the input signals, output signals, state,and time. Inherent in the definition is the notion of parameters, whichare the coefficients of the equations.

It is important to note that block diagrams are not exclusively used forrepresenting time-based dynamic systems but also for other models ofcomputation. For instance, flow-charts are block diagrams used tocapture process flow and are not generally suitable for describingdynamic system behavior. Data flow block diagrams are block diagramsthat describe a graphical programming paradigm where the availability ofdata (often thought of as tokens) is used to initiate the execution ofblocks, where a block represents an operation and a line representsexecution dependency describing the direction of data flowing betweenblocks. As used herein, the term block diagrams means time-based blockdiagrams used in the context of dynamic systems except as otherwisenoted.

Block diagram modeling has spawned a variety of software products suchas Simulink® from the MathWorks, Inc. of Natick, Mass., that cater tovarious aspects of dynamic system analysis and design. Such productsallow users to perform various types of tasks including constructingsystem models through a user-interface that allows drafting blockdiagram models, allowing augmentation of a pre-defined set of blockswith custom user-specified blocks, the use of the block diagram model tocompute and trace the temporal evolution of the dynamic system's outputs(“executing” the block diagram), and automatically producing eitherdeployable software systems or descriptions of hardware systems thatmimic the behavior of either the entire model or portions of it(referred to herein as “code generation”). Each of the tasks listedabove has many intricate details and subtle variations that are exploredfurther below.

Block modeling software includes a number of generic components.Although the discussion contained herein focuses on Simulink® version5.0 (Release 13) from the MathWorks, Inc. of, Natick Mass., thoseskilled in the art will recognize that it is applicable to other blockmodeling software applications. The generic components include a blockdiagram editor, blocks and a block diagram execution engine. The blockdiagram editor allows users to perform such actions as draw, edit,annotate, save, and print out block diagram representations of dynamicsystems. As noted earlier, blocks are the fundamental mathematicalelements of a classic block diagram model. Simulink® extends the classicblock diagram models by introducing the notion of two classes of blocks,non-virtual blocks and virtual blocks. Non-virtual blocks are elementarydynamic systems. A virtual block is provided for graphicalorganizational convenience and plays no role in the definition of thesystem of equations described by the block diagram model. Examples ofvirtual blocks are the Bus Creator virtual block and Bus Selectorvirtual block which are used to reduce block diagram clutter by managinggroups of signals as a “bundle”. Virtual blocks may be used to improvethe readability of models. Simulink® further extends the meaning of anon-virtual block to include other semantics, such as a “merge” blocksemantic. The merge block semantic is such that on a given time step itsoutput is equal to the last block to write to an input of the mergeblock. An additional extension provided by Simulink® is the concept ofconditional execution. Simulink® contains the concept of conditional anditerative sub-systems that control when in time block methods executefor a sub-section of the overall block diagram.

A block diagram execution engine contributes to the modeling softwaretask of enabling the computation and tracing of a dynamic system'soutputs from its block diagram model. An execution engine carries outthe task of compiling and linking the block diagram to produce an“in-memory executable” version of the model that is used for generatingcode and/or simulating or linearizing a block diagram model. Note thatexecution of the block-diagram is also referred to as simulation. Thecompile stage involves checking the integrity and validity of the blockinterconnections in the block diagram. In this stage, the engine alsosorts the blocks in the block diagram into hierarchical lists that areused when creating the block method execution lists. In the link stage,the execution engine uses the result of the compiled stage to allocatememory needed for the execution of the various components of the blockdiagram. The linking stage also produces block method execution liststhat are used by the simulation or linearization of the block diagram.Included within the link stage is the initialization of the model whichincludes the evaluating of “setup” methods (e.g. block start,initialize, enable, and constant output methods). The block methodexecution lists are generated because the simulation and/orlinearization of a model must execute block methods by type (not byblock) when they have a sample hit.

After linking has been performed, the execution engine may generatecode. In this stage, the execution engine may choose to translate theblock diagram model (or portions of it) into either software modules orhardware descriptions (broadly termed code). If this stage is performed,then the stages that follow use the generated code during the executionof the block diagram. If this stage is skipped completely, then theexecution engine uses an interpretive mode of execution for the blockdiagram. In some cases, the user may not proceed further with theexecution of the block diagram because they would like to deploy thecode outside the confines of the block diagram software. Upon reachingthe simulation stage, the execution engine uses a simulation loop toexecute block methods in a pre-defined ordering upon a sample hit toproduce the system responses as they change with time.

For linearization, Simulink® uses the block method execution lists in aprescribed fashion to produce a linear state space representation of thedynamic system described by the block diagram.

The block diagram editor is the graphical user interface (GUI) componentthat allows drafting of block diagram models by a user. In Simulink®,there is also a textual interface with a set of commands that allowinteraction with the graphical editor. Using this textual interface,users may write special scripts that perform automatic editingoperations on the block diagram. A user generally interacts with a setof windows that act as canvases for the model. There is generally morethan one window for a model because models may be partitioned intomultiple hierarchical levels through the use of sub-systems (discussedfurther below).

A suite of GUI tools in Simulink® allows users to draft a block diagrammodel on the corresponding windows. The GUI tools include a blockpalette, wiring line connection tool, annotation tool, formatting tool,attribute editing tool, save/load tool and publishing tool. The blockpalette is a library of all the pre-defined blocks available to the userwhen they are building the block diagram. Individual users may be ableto customize this palette to: (a) reorganize blocks in some customformat, (b) delete blocks they do not use, and (c) add custom blocksthey have designed. The palette allows blocks to be dragged through somehuman-machine interface (such as a mouse or keyboard) from the paletteon to the window (i.e., model canvas). The graphical version of theblock that is rendered on the canvas is called the icon for the block.There may be different embodiments for the block palette including atree-based browser view of all of the blocks.

The wiring line connection tool allows users to draw directed lines thatconnect the ports of blocks in the model's window. Lines are also addedthrough various mechanisms involving human-machine interfaces such asthe mouse or keyboard. Simulink® also provides various forms ofauto-connection tools that connect blocks automatically on user requestto produce an aesthetically pleasing layout of the block diagram(especially those with high complexity with large numbers of blocks).The annotation tool allows users to add notes and annotations to variousparts of the palette for a block diagram. The formatting tool enablesusers to perform various formatting operations that are generallyavailable on any document editing tool. These operations help pick andmodify the various graphical attributes of the block diagram (andconstituent blocks) such as include font-selection, alignment &justification, color selection, etc. The block diagram and all theblocks within the block diagram generally have a set of functionalattributes that are relevant for the execution or code-generation. Theattribute editing tool provides GUIs that allows these attributes to bespecified and edited. The save/load tool allows a created block diagrammodel to be saved. The saved model can be reopened in the editor at somelater juncture through a load mechanism. Simulink® also allows users tosave blocks including pre-constructed sub-systems into a separate classof block-diagrams called libraries. Such libraries facilitate reuse ofthe same block in a number of other block diagrams. The load/savemechanism is specially equipped to handle loading and saving of blocksin a block-diagram that actually reside in libraries.

The publishing tool enables the viewing of the block diagram as adocument that can be published in any of the standard document formats(examples: PostScript, PDF, HTML, etc.). Those skilled in the art willrecognize that the windows for multiple models and all of the toolsmentioned above could potentially be embedded in a single Multi-DocumentInterface (MDI) for providing a unified software environment.

Those skilled in the art will also recognize that block-diagram packagesoffer scripting languages for writing out programs that automaticallycarry out a series of operations that would normally require interactionwith the GUI. For example, Simulink® offers a set of commands in MATLABfor carrying out operations such as block addition (add_block), blockdeletion (delete_block), starting and terminating execution (set_param),modifying block attributes (set_param/get_param), etc.

Simulink® also offers a variety of other GUI tools that improve theability of users to build and manage large block diagrams. Examples ofsuch GUIs include: (a) a Finder that helps find various objects such asblocks and lines within a block-diagram, (b) a Debugger that helps debugthe execution of block-diagrams, (c) a Revision Control UI for managingmultiple revisions of the block-diagram, and (d) a Profiler for viewingtiming results while executing a block-diagram.

A typical base data-structure for a block may be represented as:

class Block {

public:

-   -   //Access methods for setting/getting block data

. . .

-   -   //Methods for block editing    -   virtual ErrorStatus BlockDrawIcon( )    -   virtual BlockParameterData BlockGetParameterData( )

. . .

-   -   //Methods for block compilation    -   //Methods for block execution

. . .

-   -   virtual ErrorStatus BlockOutput( )=0;    -   virtual ErrorStatus BlockDerivative( )=0;    -   virtual ErrorStatus BlockUpdate( )=0;

. . .

private:

-   -   BlockGraphicalData blkGraphicalAttributes;    -   BlockFunctionalData blkFunctionalAttributes;    -   BlockCompiledData blkCompiledAttributes;    -   BlockExecutionData blkExecutionData;

. . .

};

Although the example of the data structure above is written in C++,those skilled in the art will recognize that equivalent data structureswritten in other languages may also be used. The major data fields ofthe block data structure fall into four categories, a graphicalattributes field, a functional attributes field, a compiled attributesfield and an execution data field.

The graphical attributes field is responsible for storing informationrelevant for graphical rendering of the block within its parent blockdiagram's GUI. Attributes specific to the block icon such as font,color, name, and icon-image are stored in this field. It should be notedthat modifying these attributes does not affect the dynamics of themodel using this block. The functional attributes field is responsiblefor specifying block attributes that may potentially affect the dynamicsof the model using this block. These attributes are specified for theblock as a whole and the input and output ports of the block. Examplesof block attributes include block sample times and restrictive flags.Block sample times specify if the block corresponds to an elemental,continuous, discrete, or hybrid dynamic system. If the block is anelemental discrete-time system, then the attribute specifies the spacingbetween time instants at which the block response should be traced. Arestrictive flag disallows the use of blocks in certain modelingcontexts. For example, one may impose the restriction that there mayonly be one instance of given block in a model.

Attributes of block ports specify properties of the data that is eitheravailable or produced at that port. Block port attributes includedimensions, datatypes, sample rates, and direct feedthrough. Dimensionattributes are individual dimensions of a multi-dimensional matrix thatis used as a container for data elements. Datatype attributes are thedatatype of each element of data in the data container. A complexityattribute is a flag to specify if each data element is real or complex.A sample rate attribute specifies how when the signal corresponding toan input or output port will be used. The port sample times maysometimes be used to implicitly infer the block's sample time. Thedirect feedthrough attribute is specified only for input ports andindicates whether or not the Output and/or GetTimeOfNextHit equations ofthe block are a function of the given input. This attribute helps indetermining the sequence in which block methods should be executed whileexecuting the block diagram.

The compiled attributes field of the block data structure holds theattributes of the block and its ports that mirror the functionalattributes listed above. This field is filled in during block diagramcompilation by utilizing the functional attributes of the block inconjunction with the functional and compiled attributes of the blocksthat are connected to it. This process of determining the compiledattributes from the functional attributes is termed attributepropagation. Attribute propagation is described in greater detail belowin the section on block diagram compilation. The execution data field ismainly responsible for storing the memory locations that are going toserve as sources for block inputs, outputs, states, parameters, andother work areas during execution of blocks.

The block data structure also has a set of associated methods that maybe categorized as access methods to data fields, methods used inediting, methods used in compilation and methods used in execution.Access methods to data fields help in setting and getting the variousdata fields of the block. Methods used in editing are called by theblock diagram editor in order to render the block appropriately in theGUI of its parent block diagram. For instance, this set of methods mayinclude a BlockDrawIcon method that determines the shape the block iconhas on the GUI. Methods used in compilation are methods that are calledby the block diagram compilation engine. They help validate theconnections of the block to other blocks on the block diagram. Themethods used in execution include a number of different run-time methodsthat are required for execution. These include the BlockOutput,BlockUpdate, BlockDerivative methods that realize the Output, Update,and Derivative equations discussed earlier in the context of dynamicsystems. In addition to these methods, Simulink® includes several otherrun-time methods, such as the Jacobian, Projection, ZeroCrossings,Enable, Disable, Initialize, EvalParams (check and process parameters),and GetTimeOfNextHit methods. It should be noted that there is noexplicit method for algebraic equations because these are representedand processed in a different manner which will be discussed below.

The base data structure for the block specifies the generic fields andinterfaces that need to be supported by a block. Some of the methods arepurely virtual and have no specific implementation in the base blockclass. In order to define a specific block (such as an Integratorblock), one needs to subclass the base block class and provide explicitdefinitions for these virtual methods. An example of the subclassing ofa block may be seen by examining an Integrator block. FIG. 3 depicts thedesired behavior of an Integrator block 30. In order to create thesubclass, four major categories of information within the subclass mustbe specified, the block parameters, the methods used in editing, themethods used in compilation, and the methods used in execution. Theelemental dynamic system embodied by the block may be parameterized asillustrated in FIGS. 1A-1C. Each block needs to be able to specify itslist of expected parameters. The block diagram editor'sAttribute-Editing tool may allow users to specify the parameters for theblock when they use it in their models. In the Integrator block example,the block has one parameter that specifies the block's initial conditionfor the block's state. Regarding the methods used in editing, thesubclass needs to specify a method that renders its icon. For example,the Integrator block may implement a method that makes its icon be a boxwith a “1/s” within the box. Also, the subclass needs to instantiate amethod that allows access of the block parameters from the GUI'sAttribute-Editing tool. For the Integrator example, this method wouldallow users to specify the Initial Condition parameter on a GUI for theblock. For the methods used in compilation, the subclass needs toinstantiate methods that help in the compilation of the block diagrammodel in which it is placed. These methods help specify the compiledinformation for the inputs and outputs of the block. For instance, theIntegrator block may specify a method that ensures that if the input tothe Integrator is a vector, then the output is a vector of the samesize. For methods used in execution, the subclass needs to instantiatespecific Output, Derivative, and Update methods that represent the blockbehavior. In the case of the Integrator block, an Output and Derivativemethod are needed. It should be noted that in Simulink® the Integratorblock has additional methods that are not illustrated here. The Outputmethod sets the output to be equal to the state. The Derivative methodsets the derivative of the state to be equal to the input.

The specification of these four types of information for the Integratorblock subclass may be shown by a reduced form of the Simulink®Integrator block:

IntegratorBlock: public Block {

public:

-   -   ErrorStatus BlockDrawIcon( ) {        -   //Draw ‘1/s’ on the icon        -   . . .    -   }    -   BlockParameterData BlockGetParameterData( ) {        -   //Return initial_condition as block data        -   . . .    -   }    -   ErrorStatus BlockOutput( ){        -   //Implement y(t)=x(t)        -   . . .    -   }    -   ErrorStatus BlockDerivative( ){        -   //Implement dx(t)/dt=u(t)        -   . . .    -   }

private:

-   -   double initial_condition;        };

};

It should be noted that block diagram software generally provides openaccess to the block's data structure to users of the software. Thisallows users to create and utilize custom block implementations in theirmodels.

Blocks in a block diagram may be virtual or non-virtual. The designationof a block as non-virtual indicates that it influences the equations inthe mathematical model for the dynamic system. In the context of blockdiagram software, it is beneficial to include other virtual blocks thatdo not affect the equations in the dynamic system's model. Such blockshelp improve the readability and modularity of the block diagram andwield no semantic influence on the mathematical model. Examples of suchvirtual blocks include virtual sub-systems, inport blocks and outportblocks, bus creator blocks and From and Goto blocks.

Modularity may be achieved in a block diagram by layering the blockdiagram through the use of sub-systems. A sub-system facilitateslayering by allowing a collection of blocks to be represented by asingle block with input and output signals. The input and output signalsof the sub-system are accessible to the constituent blocks within thesub-system. A sub-system is a virtual sub-system if its constituentblocks are moved back into the main block diagram model during themodel's execution. Within a virtual sub-system graphical entities,called inport and outport blocks, are provided to define signalconnections to the parent block diagram. These inport and outport blocksindicate a tunnel-through signal connection to the parent block diagram.

Additional types of virtual blocks include bus creator blocks andselector blocks. In large models, there may be an extensive set of linesthat connect one section of a block diagram to another section. To avoidexcessive clutter of lines and improve readability, there is typically aspecial block called a Bus Creator that helps bundle all of the linestogether to form a single bus line. This single bus line then connectsthe two sections of the model. At the destination end of the line, ablock called a Bus Selector helps un-bundle the individual lines so thatthey can be connected to other blocks.

Other virtual blocks include From blocks and Goto blocks that arespecial blocks that help avoid graphical clutter, e.g. a line thatconnects two distant sections of a block diagram. The line is terminatedclose to its originating point by a From block. At the other end, a newline is drawn from a From block that is hot-linked to the Goto block.Each Goto and From block has an associated tag that describes whichblocks are connected together. An important point to be noted is thatvirtual blocks have neither execution data nor execution methods intheir data structure.

Simulink® also provides the user with the ability to extend thesimulator by providing the ability to enhance the simulator with blocksthat define dynamic systems or are virtual properties. The extension isprovided through a language independent API (e.g. C, C++, Ada, Fortran,Assembly, M).

As noted previously, to facilitate modeling fairly large and complexdynamic systems, Simulink® allows users to layer their block diagrams. Asub-system facilitates such layering by allowing a collection of blocksto be represented by a single block with input and output signals. Theinput and output signals of the sub-system are accessible to itsconstituent blocks. By nesting sub-systems within each other, one cancreate block diagrams with arbitrary layers of hierarchy. Ideally asub-system has no impact on the meaning of the block diagram.Additionally, sub-systems provide a way of grouping blocks together andallowing other block diagram constructs to impose unified control on theconstituent blocks. To enhance the modularity of sub-systems, modelingsoftware also allows aggregated list(s) of parameters of the blockswithin the sub-system to be accessed from a single GUI, and defines anddisplays special icons on the sub-systems. The process of defining theparameter list and the special icon is called masking a sub-system.

There are two main types of sub-system blocks, virtual sub-systems andnon-virtual sub-systems. Virtual sub-systems serve the purpose ofproviding the block diagram with a graphical hierarchy. Non-virtualsub-systems behave like an elemental dynamic system with its ownexecution methods (Output, Update, Derivatives, etc.). These executionmethods in turn call the execution methods of the constituent blocks.

The classes of non-virtual sub-systems are:

Atomic sub-systems. These are similar to virtual sub-systems, with theadvantage of grouping functional aspects of models at a given layer.This is useful in modular design.

Conditionally-executed sub-systems. These are non-virtual sub-systemsthat execute only when a precondition is fulfilled:

Enabled sub-systems. These are similar to Atomic sub-systems, exceptthat the constituent blocks only execute when an enable signal feedingthe sub-system is greater than zero.

Triggered sub-systems. These are similar to Atomic sub-systems, exceptthat the constituent blocks only execute when a rising and/or fallingsignal is seen on a triggering signal feeding the sub-system.

Enable with Trigger sub-systems. These are an intersection of theproperties of Enabled and Triggered sub-systems.

Action sub-systems. These sub-systems are connected to action-initiator(e.g., an “If” or “SwitchCase” block), a block that explicitly commandsthe sub-system contents to execute. These sub-systems are similar toEnabled sub-systems except that the management of the “enabling” signalhas been delegated to an action-initiator. Action sub-systems define anew type of signal, called an action signal that signifies whichsub-systems are commanded to execute by the action-initiator.Function-call sub-systems. These sub-systems provide a means ofcollecting blocks into a sub-system that is only executed when called byan owner block. The owner block may compute input signals for thesub-system before calling the sub-system. Additionally, the owner mayalso read output signals from the sub-system after calling it.Function-call sub-systems define a new type of execution control signal,called a function-call signal that contains no data. It is used todefine the execution relationship between the owner block and thefunction-call sub-system. Function-call owners may also designatethemselves as an “interrupt” source. In simulation, they simulate theeffects of an interrupt and in code generation they can attachthemselves to an (asynchronous) interrupt.While sub-systems and For sub-systems. These sub-systems execute theconstituent blocks multiple times on a given time step.

Simulink® allows for several forms of block parameters to be defined.There are two general categories of parameters: those parameters thatcan be modified during simulation and those that cannot be modified. Anexample of a parameter that may be modified during simulation is theamplitude of a Sine Wave block if configured by the user to allowmodification during execution. A parameter such as the amplitudespecifies coefficients of the dynamic equation, in this case theamplitude of the sine wave function defined by the Sine Wave block. Anexample of a parameter that can never be modified during simulation isthe sample time of the Sine Wave block. The parameters that can bemodified during simulation are further broken down into other categorieswhich include mapping the dialog parameter (e.g. the amplitude) torun-time parameters or converting the dialog parameter to an inlined(non-modifiable) parameter. Run-time parameters can further be mapped tomathematical expressions of tunable Matlab variables or Matlab parameterobjects describing properties of the variables (calledSimulink®.Parameter's). A global run-time parameter data structure isused within Simulink® to manage the block parameters during theexecution of the model.

In addition to block parameters, there are model-wide parameters thatare generally associated with the solver. These parameters includeaspects such as the time span in which to perform a simulation, the typeof solver, and the time span. Simulink® gives the user the ability toadjust solver parameters during model execution. The adjustment of thesesolver parameters is performed at the start of a time step.

Once a block diagram model has been constructed using the editor, anexecution engine allows the model to be solved in order to trace thesystem outputs as a function of time. The solution of the model, whichmay be referred to as model execution, is carried out over auser-specified time span for a set of user-specified inputs. Simulationproceeds in four major stages: compilation, link, code generation, andthe simulation loop. Alternatively, the execution engine can obtain alinear representation of the model (linearization). Theinterrelationship between the various stages is illustrated in aflowchart in FIG. 4.

The execution begins when the block diagram 40 is compiled 42. Followingthe compilation stage, is the model link stage 44 which may also producelinear models 46. Code may or may not be generated 45. If code isgenerated 48, a decision is made 49 whether to continue the simulation.If the decision is made to continue the simulation the model issimulated/executed through the Simulation Loop 50. If the simulation isnot continued, the code may be delivered to a target 52 and executed inan external mode 54. If code is not generated the block diagram mayexecute in interpretive mode when entering the Simulation Loop 50.

The compile stage marks the start of model execution and involvespreparing data structures and evaluating parameters, configuring andpropagating block characteristics, determining block connectivity, andperforming block reduction and block insertion. The preparation of datastructures and the evaluation of parameters creates and initializesbasic data-structures needed in the compile stage. For each of theblocks, a method forces the block to evaluate all of its parameters.This method is called for all blocks in the block diagram. If there areany unresolved parameters, execution errors are thrown at this point.

During the configuration and propagation of block and port/signalcharacteristics, the compiled attributes (such as dimensions, datatypes,complexity, or sample time) of each block (and/or ports) are setup onthe basis of the corresponding functional attributes and the attributesof blocks (and/or ports) that are connected to the given block throughlines. The attribute setup is performed through a process during whichblock functional attributes “ripple through” the block diagram from oneblock to the next following signal connectivity. This process (referredto herein as “propagation”), serves two purposes. In the case of a blockthat has explicitly specified its block (or its ports') functionalattributes, propagation helps ensure that the attributes of this blockare compatible with the attributes of the blocks connected to it. Ifnot, an error is issued. For instance, if an Integrator block isimplemented to only accept numbers of double precision datatype, thenthis block will error out if it is driven by a block that producessingle precision data, unless the user has asked for an implicit dataconversion. Secondly, in many cases blocks are implemented to becompatible with a wide range of attributes. Such blocks adapt theirbehavior in accordance with the attributes of the blocks connected tothem. This is akin to the concept of polymorphism in object-orientedprogramming languages. For instance, a discrete-time Filter block couldbe implemented to accept any of the standard integer datatypes rangingfrom 8-bit to 128-bit. The exact implementation of the block is chosenon the basis of the specific block diagram in which this block findsitself. Included within this step are other aspects such as validatingthat all rate-transitions within the model yield deterministic resultsand that the appropriate rate transition blocks are being used.

The compilation step also determines actual block connectivity. Virtualblocks play no semantic role in the execution of a block diagram. Inthis step, the virtual blocks in the block diagram are optimized away(removed) and the remaining non-virtual blocks are reconnected to eachother appropriately. This compiled version of the block diagram withactual block connections is used from this point forward in theexecution process

Once actual block connectivity has been determined (by removing thevirtual blocks) the block diagram may be further optimized by performingblock reduction and insertion. During this step, non-virtual blocks maybe inserted or a set of non-virtual blocks may be completely removed orreduced to a single equivalent block. Block insertion and reduction ismainly done to improve execution efficiency. Examples of block insertionand reduction include the removal of Gain blocks whose gain value is 1.

A Gain block is a block that multiplies its input value by a gainparameter, such as a simple amplifier. FIG. 5 depicts the replacement ofa collection of blocks 60, 62, and 64 connected in a accumulator patternand leading to result 66 with an equivalent synthesized block 68representing the accumulator pattern leading to the same result 66. Asignal copy block may also be automatically inserted in order to makecontiguous memory copies of signals that are made up of disjoint memorysections. Block insertion and reduction may also be performed at othersuitable stages of compilation.

The way in which blocks are interconnected in the block diagram does notnecessarily define the order in which the equations (methods)corresponding to the individual blocks will be solved (executed). Theactual order is partially determined during the sorting step incompilation. Once the compilation step has completed, the sorted ordercannot be changed for the entire duration of the block diagram'sexecution.

The first step in sorting involves transforming the graphical blockdiagram into a compiled (in-memory) directed graph consisting of arcsand vertices. The vertices are derived from some of the non-virtualblocks. For instance, virtual and reduced blocks do not appear in thedirected graph. The arcs represent data dependencies between thevertices. The data dependencies do not correspond to the signals in theblock diagram. For example, all signals that connect to input portswithout direct feed through are “cut” or ignored. In addition, datadependencies are added to capture implicit dependencies. For example,all inputs to a Function-Call sub-system are implicit data dependenciesto the owner (caller) block.

The process of converting a block diagram into a compiled directed graphis shown in FIG. 6A. A block diagram 81 includes a Sine Wave1 block 82,a Sine Wave 2 block 84, a Goto block 86, a Function Call Generator block88, and a From block 90. Also included are a Function Call Sub-systemblock 92, a Sum block 94, a Gain block 96, an Integrator block 98 and anOutport (Output 1) block 100. Those blocks that are not virtual orreduced appear on the corresponding directed graph 111. The directedgraph 111 includes a Sine Wave 1 vertice 112, a Sine Wave 2 vertice 114,a function-call generator vertice 116, and a function call sub-systemvertice 118. Also included are a Sum vertice 120, a Gain vertice 122, anIntegrator vertice 124 and an Outport 1 vertice 126. The vertices areconnected by arcs.

The graph is used to sort the blocks into a linear sorted list. FIG. 6Bdepicts a sorted list 128 generated from the compiled directed graph 111which includes the elements appearing as vertices in the directed graph111 sorted into order. The root block diagram has a sorted-listassociated with it. Roughly speaking, each non-virtual sub-system layerand some special block diagram elements also each have their ownsorted-list. During the sorting of the graph into the list, stronglyconnected components are identified. The term strongly connectedsection, which is a term that originates from graph theory, is a subset,S, of the blocks of a block diagram such that any block in S isreachable from any other block in S by following signal connections andS is not a subset of any larger such set. Strongly connected sectionsare flagged as algebraic loops when all blocks have direct feedthrough(an example is shown in FIG. 6A consisting of the Sum 120 and Gain 122blocks). Such loops correspond to a set of algebraic equations and aresolved using iterations and perturbations during block diagram executionby solving for the algebraic variables. Algebraic variables are eitherspecified by the user via Initial Condition blocks or chosen by theexecution engine. Solving of algebraic loops is discussed further below.

Sorting must also take into consideration other user specifieddependencies between the blocks. These dependencies include the conceptsof priorities and placement groups. A block priority specifies the orderin which the equations associated with a block are evaluated withrespect to other blocks. Placement groups are a way of causing eachclass of block methods for a specified set of blocks to be “placedtogether” in the block method execution lists. The terms “datadependency” or “data precedence” as used herein refers to the arcs ofthe compiled directed graph and not the signals found within a blockdiagram. Attempting to correlate data dependencies directly to thesignals found within a block diagram is incorrect and leads to theconclusion that Simulink® does not satisfy data dependencies, i.e., theexecution of the operations or block methods does not satisfy datadependencies if one interprets signal connectivity as specifying datadependencies.

After compilation, the link stage commences. During this stage physicalmemory allocations are made in order to prepare for execution. Buffersare allocated for block input and output data buffers, states, and workareas. Additionally, block method execution lists that are derived fromthe sorted list allow for execution of the block diagram. Each blockmethod execution list is a list of block methods that are to be executedin a sequence when each method within the list has a sample hit. Thereis generally a set of block method execution lists associated with eachlayer of the block diagram that corresponds to a non-virtual sub-system.Non-virtual sub-systems are either defined by the user or automaticallysynthesized during compilation to either efficiently execute the modelor simplify the implementation of the semantics defined by Simulink®. Inmulti-tasking mode, the lists within each layer may be furtherpartitioned when block diagrams have blocks with different sample rates.These lists are explained in greater detail below.

Those skilled in the art will recognize that while the block methodexecution lists are derived from the sorted list, they do notnecessarily correspond one-to-one with the sorted lists. First, eachblock method execution lists contains only blocks that have such a blockmethod of the given type (class) defined by the list. Second, blockmethods corresponding to components like the function-call sub-system donot appear on the block method execution lists because they are executedby an “owner” block.

Although included in the discussion of the compilation stage, it is notrequired that the time-based diagram perform the block sorting stepduring compilation. The sorting step is performed to achieve efficientexecution. Ignoring efficiency, there is no semantic reason to performthe sorting step. Any random ordering of the block methods will work. Infact, any ordering of all block method execution lists except the Outputblock method execution list will result in the same level of efficiency.Randomly re-ordering the Output block method execution list will yieldcorrect answers. If the Output block method list is randomly ordered,then the Simulation engine, when executing the Output block methodexecution list, continues sequencing through the Output block methodexecution list at each point in time until there are no changes.

Similarly included within the linking stage for the sake of simplicity,is the memory initialization of the model. The memory initialization ofthe model includes invoking block start, initialize, constantinitialize, enable, and constant output methods. These are examples ofsome of the block methods that are used during model setup (prior toexecution) to initialize the “state” of the system so that execution orlinearization can commence.

The compiled and linked version of the block diagram may be directlyutilized to execute the model over the desired time-span. Thisinterpretive mode of execution is suitable for getting fine-grainedsignal traceability. It should be noted that the traceability associatedwith interpretive execution comes at the price of increased overhead inthe form of additional execution-related data-structures and messagingin the engine. An alternative to the interpretive execution mode is toutilize the generated-code created by Real-Time Workshop tool forSimulink® models. In this mode, the engine (upon the behest of the user)translates a selected portion of the block diagram (or the entire blockdiagram itself) into code. Such code could be in a number of possibleforms. The code may be instructions in a high-level software languagesuch as C, C++, Ada, etc., hardware descriptions of the block diagramportions in a language such as HDL, or custom code formats suitable forinterpretation in some third-party software. Alternatively, the code maybe instructions suitable for a hardware platform such as amicroprocessor, microcontroller, or digital signal processor, etc., aplatform independent assembly that can be re-targeted to otherenvironments, or just-in-time code (instructions) that corresponds tosections of the block diagram for accelerated performance.

The execution of a portion of the block diagram represented in code maybe performed in a number of different ways based on the specific codeformat. The portion of the block diagram may execute a compiled versionof the code generated in a high-level language (accelerated orsoftware-in-the-loop simulation), the execution may simulate code thatcorresponds to a hardware description on a hardware simulator,(co-simulation execution), the execution may involve calling out tothird-party software to run code generated for such software(co-simulation execution), or the execution may call out directly tohardware that will run code that was generated and compiled for thathardware (processor-in-the-loop execution).

There are several different advantages to execution through codegeneration: Execution of generated code can be more efficient thaninterpretive execution because of fewer data-structures and lesserinternal messaging in the engine, although the increased efficiencygenerally comes at the cost of decreased execution traceability.Simulation of hardware descriptions during execution can help identifyand resolve bugs in the software stage of a design project. Such bugsprove much more expensive to track and fix once the system has beenimplemented in hardware. Additionally, block diagram modeling softwarecan be integrated with other software environments that are suitable formodeling and simulating special classes of systems. Models can be testeddirectly in hardware thereby making prototyping of new systems fast andcost-effective. For instance, consider the design of a controller for ananti-lock braking system of a car. The dynamics of the braking systemcan be executed in the interpretive mode in the block diagram. Thecontroller itself can be implemented on a hardware micro-controller totest the efficiency of the control laws implemented within. Note thatfor such target execution, it is normally necessary for the time spanover which a model is executed by the software to match real-world time.In other words, the software must allow real-time execution of the blockdiagram model. Those skilled in the art will recognize that when usersgenerate code, they may choose to not proceed further with the blockdiagram's execution. They may choose to take the code and deploy itoutside of the confines of the modeling software environment. This isnormally the last step in the design of dynamic systems in a blockdiagram software package.

There are several forms of target code execution known to those skilledin the art such as Rapid Prototyping, Embedded System Deployment, andHardware-in-the-Loop which execute a model or portions of a model viathe generated code on a Real-Time System target. One aspect of deploying(executing) the generated code on a target is the notion of “externalmode.” External mode refers to a system where Simulink® acts as amonitor and debugger of the generated code running in real-time on atarget. In External Mode, users can change parameters and view signalsvia standard Simulink® elements. Another important aspect of the codegeneration technology is that it is very extensible. Provided with theSimulink® product family is the Target Language Compiler (TLC). Thistechnology enables the creation of “active scripts” that control how thegenerated code is produced for a block diagram. Using TLC, one cantailor the generated code to suit their specific needs.

The execution of the block diagram uses a Simulation Loop (SimLoop) forsolving for the block diagram's outputs for a specified set of inputsover a specified span of time (“Time” in reference to the SimulationLoop means the time-line corresponding to the tracing of the dynamicsystem's outputs, not real-world time unless otherwise noted). The term“SimLoop” applies to real-time systems where each iteration is tied to aphysical periodic clock or other timer source. During this process, theblock methods (equations) corresponding to the individual blocks areexecuted by type following their sorted order when they have a samplehit. The term “block execution” is loosely used to mean executing allblock methods associated with the given block for a given time step,generally starting with the output method. Strictly speaking, blocks donot execute; the engine executes (evaluates) the appropriate blockmethods at the appropriate time points.

SimLoop has two variants “single-tasking” and “multi-tasking” dependingon sample times. In general, the sample time of a block is the intervalof time between calls to the Output, Update, and/or Derivative methodsfor a given block. In computing this interval, repeated calls at thesame time instant (not in real-world time but the time corresponding tothe execution of the dynamic system) are counted as the same call. Ablock's sample rate may also be thought of as the interval betweensuccessive executions of the block methods. If there is no uniform orregular interval between calls, then the block is said have a continuoussample time. If a uniform time interval can be found, then the block issaid to have a discrete sample time equal to that interval. Althoughblocks may be associated with more than one sample time in asufficiently complex dynamic system the descriptions contained hereinare confined to blocks with a single sample-time. Those skilled in theart will recognize that the descriptions may be extended to encompassblocks with multiple sample times.

FIG. 7A depicts an abstract example of a block diagram being executed.The diagram includes a plurality of blocks 140, 142, 144, 146, 148 and150. The block ports that have direct feedthrough are explicitly marked(using the symbol “df”) 152. Additionally, an abstract view of theexecution methods instantiated by each block is shown in FIG. 7B. Theblocks contain a number of different methods 160, 162, 164, 166 and 168.Execution methods includes the three basic execution methods discussedearlier: Output, Update, Derivative, as well as several other methodsthat aid in advanced block functions such as initialization,linearization and zero-crossing detection which are discussed below).The data-dependencies between the compiled vertices created duringsorting are used to generate the Sorted List 170 shown in FIG. 7C.

A block diagram consisting of blocks that all have the same sample timeis said to correspond to a single-rate system. A block diagramconsisting of blocks that have more than one sample time corresponds toa multi-rate system. FIG. 8 depicts a multi-rate system, addingsample-time information to the block diagram of FIG. 7A. The pluralityof blocks 140, 142, 144, 146, 148, and 150 each have an associatedsample time. Since the sample times in the block diagram differ betweenblocks, the system is considered a multi-rate system. Block A 140, blockE 148 and block F 150 each have a sample time of 0.1 seconds. Block B142, block C 144 and block D 146 each have a sample time of 1.0 seconds.

The SimLoop is the heart of the execution engine. Each full pass throughthe loop is responsible for computing the outputs of the system at aparticular time. At the end of each loop, the execution timecorresponding to the next pass through the loop is computed. If thistime exceeds the stop time specified by the user, the executionterminates. Within the loop, the sequence in which individual blockequations are solved is determined by two pieces of information: thesample times of the blocks and the sorted order determined during theCompile stage. The amalgamation of these two pieces of information givesthe execution lists for the block diagram. Those skilled in the art willrecognize that the execution lists are created in the Link stage and areexplained in the context of SimLoops for convenience. There are twodistinct approaches for building execution lists and using them in theSimLoop. These approaches correspond to the Single-tasking andMulti-tasking SimLoops summarized in the discussion on FIG. 10 below.

Simulink® also has the ability to modify coefficients (parameters) ofblocks that declare their parameters as tunable. An example of such ablock is a Sine Wave block that implements the function: output(time)=amplitude*sin(frequency*time+phase)+bias, where time is theindependent variable and the parameters are: amplitude, frequency,phase, bias. When these parameters are declared as tunable, Simulink®lets the user change these coefficients during simulation. Changingparameters is a drastic operation in that the definition of the modelhas changed (e.g. the sine block defines equations that describe thesystem). Thus, to enable the changing of parameters during the SimLoop®,Simulink® first queues parameter changes and then applies them on thenext time step. Thus, the changing of parameters is not immediate. Thedelay in the changing of parameters is needed to ensure systemstability. The application of the parameters at the start of the nexttime step is combined with the reset of the solver (Integrator) ifneeded.

For the purpose of exploring single-task loops and multi-task loops,FIG. 9 depicts the block diagrams of FIG. 7A and FIG. 8 where Method1corresponds to the Output method 190 and Method2 corresponds to theUpdate method 192. All other methods are ignored in the explanation ofthe loops. Simpler loops which do not include blocks that havecontinuous sample times are used in the example since the explanation issimpler in the context of discrete sample times and it isstraight-forward to extend to continuous sample times.

In a single-tasking SimLoop, there is essentially a single executiontime-line. On this time-line, each block is executed when it has asample hit. A sample hit is defined to be an execution time instant thatis an integer multiple of the block's sample time. To aid in execution,execution lists are constructed for each method type. FIG. 10 depictsthe sequence of steps followed by a single-tasking execution loop.Following initialization (step 200), a time parameter is checked to seeif the current time is less than the stop time (step 201). If the timeis not less than the stop time, the simulation ends (step 202). If thetime is less than the stop time, the simulation continues and the rootoutput method execution list is executed (step 204). Following executionof the output method list (step 204) the update method execution list isexecuted (step 206). Following the performance of an integrate step(208) (the Integrate step is described in more detail below in FIG. 14),the time parameter is incremented by the applicable step size (step210).

Blocks are arranged in the single-tasking execution lists in the sortedorder as shown in FIG. 11A. A sorted list 250 is used to generate anOutput method execution list 252 and an Update method execution list254. Referring back to the example in FIGS. 7 and 8, the enginesequentially steps through and execute each block in the block methodexecution list when the execution time divided by the sample time equalsan integer number (1, 2, 3, 4, etc.). At time zero (T₀), all the blocksare executed. This involves executing the Output methods for blocks F,E, D, A, B, and C (in this order as dictated by the sorted list) andthen executing the Update methods of blocks F, E, and D (again, in thisorder based on the sorted list). The execution time then is thenincremented by step size, which in this case is assumed to be 0.1seconds. Execution then commences once again at the top of the loop forT=0.1 (T_(0.1)). Blocks F and E have a sample time of 0.1 seconds andhave a sample hit (0.1÷0.1=1, sample time is an integer multiple of theexecution time), so the output block methods for Blocks F and E areexecuted. Block D, however, has a 1.0 second sample time and has nosample hit (0.1÷1.0=0.1, sample time is not an integer multiple of theexecution time), so its output block method is not executed (essentiallyit is skipped). Block A, like Blocks F and E, has a 0.1 second sampletime and so its output block method is executed. Blocks B and C, likeBlock D, have 1.0 second sample times and are skipped during thisiteration of the simulation loop, which completes execution of theoutput block method execution list for T_(0.1).

The execution timing of the example block diagram in single task mode isshown in the first time-line of FIG. 11B. In this diagram, note that theexecution-time is not synchronized with real-world time. Instead,execution time progresses as fast as it can in real-world time. Thesorted list 259 is executed on the time-line 260. The methods in thelist 262 are executed at the appropriate time step 264. Block diagrammodeling software can also allow users to simulate real-world conditionsby synchronizing execution time with real-world time. Such execution isillustrated in the second timing diagram of FIG. 11B. The methods 262are implemented at a time-step 264 synchronized with real world time onthe time line 270.

In multitask mode, the engine performs execution along multipletime-lines based upon the number of block sample times used in the modeas shown in the flowchart of FIG. 13. In the example of FIGS. 7 and 8,the model's blocks have a sample time of either 0.1 seconds or 1.0second. This implies that the engine runs one set of blocks along a 0.1second time line and another set of blocks along a 1.0 second time line.In order to run in multitask mode, the execution lists are first dividedon the basis of methods (as in single-tasking mode) and then subdividedagain based upon block sample times. This is illustrated in FIG. 12A.The sorted list 280 is used to generate an output method execution list282 and update method execution list 288. The output method executionlist 282 is split into two separate list execution lists 284 and 286based on sample times. Similarly, the update method execution list 288is divided into two update method execution lists 290 and 292 based onsample times.

The execution engine uses the divided execution lists to create multipleexecution time lines. In the multitask mode the engine places a higherexecution priority on the faster sample time blocks than the slowersample time blocks. This prioritization is carried out by assigning TaskIdentification Numbers (TIDs) to each execution list; the higher thepriority, the lower the TID. For example, a TID of 0 executes at ahigher priority than a TID of 1, and so forth. Furthermore, because,during execution in multitask mode, execution transitions between thefaster and slower blocks, and vice-versa, the multitask mode requiresrate transition blocks that allow the model to transition from blocksrunning at fast sample times, in our example 0.1 seconds, to slowersamples times, e.g., 1.0 seconds. The rate transition blocks arerequired to correctly simulate how a multi-rate system would behave in areal-time environment. To provide this transition, the engine promotesrate transition blocks to the TID of the fast block for which transitionis being provided, although the engine executes these rate transitionblocks at their slower rate. This is why Blocks D and B appear in the0.1 sample time output method execution list in FIG. 12A.

The execution of our example in the multi-task mode may be seen in FIG.12B. At time T=0, the engine first executes the high priority outputmethods (those with TID 0) for Blocks F, E, D, A and B, then it executesthe high priority update methods (those with TID 0) for Blocks F and E.After finishing the high priority blocks, the engine executes the lowerpriority output block methods (those with TID 1) for Block C, and thenexecutes the lower priority update methods (those with TID 1), which, inthis example, is Block D. In contrast to the single task mode, inmultitask mode the engine runs through a TID inner loop to execute theoutput and update block methods before going on to the Integration step,as the flow chart in FIG. 13 which is discussed below illustrates.

As a result of the inner TID loop, as well as the segregated blockmethod execution lists, the order of execution in multitask mode differsfrom the order of execution in single task mode. Recall for the examplethat in single task mode that the order of execution at T=0 is: F_(o),E_(o), D_(o), A_(o), B_(o), C_(o), F_(u), E_(u), and D_(u), where thesubscript “o” stands for output method and the subscript “u” stands forupdate method. In the multitask mode, however, the order of execution atT=0 is: F_(o), E₀, D_(o), A_(o), B_(o), F_(u), E_(u), C_(o), and D_(u).Notice that C_(o) is executed in a different order in multitasking mode.This occurs because separate method execution lists (based upon sampletime) are created and run in order from fastest sample time to slowestsample time. Additionally, the use of rate transition blocks restrictsthe connection of blocks with different rates. By requiring theinsertion of these blocks into the model, the engine ensures thatexecution in multitask mode will follow the sorted list.

After it is finished executing the block methods for T=0, like in thesingle task mode, the execution time is incremented (again assume by 0.1seconds) and execution goes to the beginning of the loop. The engineexecutes F₀, E₀, A_(o), F_(u), and E_(u), and the engine does notexecute the block methods of Blocks D, B, and C because the currentexecution time is not an integer multiple of those block's sample time.The engine repeats this execution until the execution time isincremented to 1.0 seconds, whereupon execution occurs in the samemanner as described for T=0. The engine repeats this overall processuntil the execution stop time is reached.

FIG. 12B shows two time-lines; the lower time-line 306 represents theexecution order of the faster sample time blocks (Blocks A, E, and F),along with the rate transition blocks (Blocks B and D), while the toptime-line 308 shows the execution order of the slower sample time block(Block C), and the rate transition (Block D) update method. Thetime-lines are generated from the sorted list 302 and the associatedsample times 304. The lower line, representing the faster sample timeshas a TID of 0, and the top line has a TID of 1. For execution time T=0,the chart shows that the engine executes the output methods for BlocksF, E, D, A, and B (designated on the chart as F_(o), E_(o), D_(o),A_(o), B_(o)). Then, consistent with the flow chart for themulti-tasking mode (see FIG. 13 discussed below), the engine executesthe update block methods for Blocks F and E (designated F_(u), andE_(u)). Once the engine is finished with the high priority blockmethods, the output method for Block C (C_(o)) and the update method forrate transition block D (D_(u)) are executed. The execution time is thenincremented by the step size (continue to assume 0.1 seconds) and theblocks that have a sample hit are executed. The figure shows executionof F_(o), E₀, A_(o), F_(u), and E_(u), which is repeated, as notedabove, until execution time equals 1.0 second. Notice, like in thenon-real-time case for Single-task mode, the engine does not wait fortime to elapse; rather it executes block methods immediately uponcompletion of the previous pass through the loop.

FIG. 13 shows the overall sequence of steps taken by Simulink® inmultitask mode. Following initialization (step 220), the output methodexecution list is executed for the fastest sample time (step 222). Theupdate method execution list is then executed for the fastest sampletime (step 224). A time parameter is checked (step 225) to determine ifthe time is less than a designated stop time. If the stop time has beenreached, the simulation completes (step 226). Otherwise, the integratestage (step 228) is performed. The task ID variable is incremented (step230) and compared to a parameter of the number of sample times (step231). If the task ID is less than the number of sample times, the outputmethod execution list for the methods assigned the new task Id areexecuted (step 232) followed by the execution of the update methodexecution list assigned the new task ID (step 234). The task ID variableis incremented and the process iterates with the task ID being comparedto the number of sample rate times (step 231). When the task ID numberis determined to equal the number of sample rate times, the simulationtime is incremented (step 238) and the entire process iterates with theoutput method list execution list (step 222) being executed for thefastest sample times. The process continues until the end of simulationwhen the time equals the stop time (step 226).

In order to understand how the step size is picked within SimLoop, it isfirst necessary to understand the notion of a solver. The solver is amodule of the execution engine that is responsible for performing twotasks: (a) determining how far execution time should be advanced betweenconsecutive passes through the SimLoop in order to accurately trace thesystem's outputs, and (b) integrating the derivative of the states ofthe system to obtain the actual states. Based on how solvers perform thefirst task, they are generally classified into two basic classes:Fixed-step solvers or Variable-step solvers.

Fixed-step solvers are solvers in which the time step-size betweenconsecutive passes through the SimLoop is a fixed quantity. The usergenerally explicitly specifies this quantity. These solvers are used tomodel types of systems that must operate within a defined time (discretesystems). For instance, an anti-lock braking system may be designed tocontrol a car's braking system, and to execute such control in one-onehundredth (0.01) of a second so as to assure the car stops safely; ifthe braking system does not meet its timing constraints, the car maycrash. Fixed-step solvers, therefore, are designed to help modeldiscrete systems that have to generate a result in a fixed time period,and the fixed-step execution assures that the modeled system cangenerate such results.

Variable-step solvers are designed to model continuous systems wherenon-evenly spaced time steps are needed to simulate all significantbehavior. For example, one may want to simulate the path of a bouncingball, where it bounces, how high it bounces, and where it stops. It isknown, based on experience, that the ball's bounces will not be evenlyspaced, and that the height of the bounces will diminish as a result ofgravity, friction, and other forces. Variable-step solvers are used forthese types of continuous systems and to determine what step size to useso that the behavior of the ball will be accurately modeled.

The two broad classes of solvers are further subdivided based on theintegration task they perform. There are several algorithms for carryingout numerical integration.

The particular choice of the integration algorithm gives rise to thesubclasses of solvers.

The difference in the conceptual definition of Fixed- and Variable-stepsolvers leads to the functional difference in the context of theSimLoop. The major difference between the solvers arises in theIntegrate step of the SimLoop which is depicted in FIG. 14. During theIntegrate step, the Variable-step solver executes the Output andDerivative block method lists for a number of iterations that variesbased on the solver subclass (i.e., the numerical integration algorithmit uses) and integration error tolerances. In a fixed-step solver, thenumber of iterations is fixed for a given solver subclass. Anotherdifference between solvers arises in the Integrate phase in the contextof an operation known as zero-crossing detection. Zero-crossings in thederivatives of the state generally indicate a discontinuity in thestates themselves. Because discontinuities often indicate a significantchange in a dynamic system, it is important to trace the system outputsprecisely at such points. Otherwise, the outputs of the model could leadto false conclusions about the behavior of the system underinvestigation. Consider, again the example of the bouncing ball. If thepoint at which the ball hits the floor occurs between simulation steps,the simulated ball appears to reverse position in midair. This mightlead an investigator to false conclusions about the physics of thebouncing ball. To avoid such misleading conclusions, it is importantthat the execution has time steps on and around the vicinity ofdiscontinuities.

In the case of Fixed-step solvers, there is no notion of zero-crossingdetection and one is not guaranteed to find all points of discontinuity.One can only keep reducing the step-size to increase the probability ofhitting the discontinuity. Contrastingly, in the case of Variable-stepsolvers, the Integrate step explicitly includes zero-crossing detection.The execution step size is then adjusted accordingly to ensure thatdiscontinuities are tracked accurately. To enable zero-crossingdetection, blocks that can produce discontinuities instantiate a specialexecution method. This method registers a set of zero-crossing variableswith the execution engine, each of which is a function of a statevariable that can have a discontinuity. The zero-crossing functionpasses through zero from a positive or negative value when thecorresponding discontinuity occurs. During the zero-crossing detectionphase of the Integration step, the engine asks each block that hasregistered zero-crossing variables to update the variables for theprojected time of the next time step. These variables are then checkedfor a change of sign since the current step. Such a change indicates thepresence of a discontinuity. An iterative process then tries to narrowdown the location of the discontinuity and ensure that the next few timesteps (at least 2) accurately bracket the location of the discontinuity.The final difference, which is in the step-size during execution, is adirect consequence of the two previous differences in the step-sizedetermination. In Fixed-step solvers, the step size is a known and fixedquantity. For Variable-step solvers, the step size is determined duringthe integration iterations and the zero-crossing detection that happensduring the Integration step.

An example of the variable-step solver is shown in FIG. 14, thederivative method execution list is executed (step 240) followed by theoutput method execution list (step 242). The derivative method executionlist is then executed again (step 244) and the solver iterates betweenthe execution of the output method execution list (step 242) and theexecution of the derivative method execution list (step 244). A similariteration loop then occurs between the execution of the output methodexecution list (step 246) and the execution of the zero-crossing methodexecution list (step 248). Note that Simulink® also includes othermethods such as Projections and Jacobians in this step as needed.

While it is theoretically possible to have Variable-step solvers in thecontext of multitasking, such a combination is not employed in practice.This is because the step-size for such solvers can become very smallmaking it impossible to keep up with the real-time constraint thatgenerally goes along with multitasking execution. An added complicationis that the integration step in such solvers is iterative and takesvarying amounts of time at each step of the execution. Therefore,Variable-step solvers are generally used only in conjunction with theSingle-Tasking SimLoop. Additionally, they are not usually employed insystems that need to operate in real-time.

When a model contains an algebraic loop, the engine calls a loop solvingroutine at each time step. The loop solver performs iterations andperturbations to determine the solution to the algebraic condition (ifit can). One possible approach to solving the algebraic equation F(z)=0,is to use Newton's method with weak line search and rank-one updates toa Jacobian matrix of partial derivatives. Although the method is robust,it is possible to create loops for which the loop solver will notconverge without a good initial guess for the algebraic states z.Special blocks are generally provided to specify an initial guess of thestates in the algebraic loop.

In addition to the various forms of the SimLoop, modeling packages suchas Simulink® use the output of the Link stage to compute linear modelsthrough a process generally referred to as model linearization. Theselinear models may be used in the SimLoop at various points in theexecution of the overall model. Alternatively, the linear model may bereturned to the user. The linearization process involves the use of aJacobian method defined on blocks and numerical Jacobian algorithm.

Information related to the compiled block diagram may be presented tousers in an automatically generated report. This report allows users toquickly obtain documentation of the functional description of theirmodel. Information related to the execution of a particular model (suchat the time taken to execute various portions of the model and thecoverage of various portions of the model) may be obtained automaticallyand presented to the user as a report.

As previously mentioned above, a dynamic system can be simulated using ablock diagram, and code can be automatically generated to represent theblock diagram structure in a textual format, and ultimately to perform amodel or simulation execution. Simulating a dynamic system in agraphical programming environment is typically a two-step process.First, a user creates a graphical model, such as a block diagram, of thesystem to be simulated. A graphical model may be created using agraphical user interface, such as a graphical model editor. Thegraphical model depicts time-based relationships between the systemsinputs, states, parameters and outputs. After creation of the graphicalmodel, the behavior of the dynamic system over a specified time periodis simulated using the information entered into the graphical model. Inthis step, the graphical model is used to compute and trace the temporalevolution of the dynamic systems' outputs (“execute the graphicalmodel”), and automatically produce either deployable software systems ordescriptions of hardware systems that mimic the behavior of either theentire model or portions of the model (code generation).

Block diagrams are graphical entities having an “executable meaning”that are created within graphical programming environments for modelinga dynamic system, and generally comprise one or more graphical objects.For example and as previously discussed, in Simulink®, a model of adynamic system is a block diagram comprising a number of graphicalobjects. Generally, a block diagram comprises a plurality of nodes,called blocks, which are interconnected by lines that represent signals.In Simulink®, each block represents a functional entity, such as anelementary dynamic system, which implements a mathematical operation,i.e., an algorithm or equation, on the data being processed by thesystem represented by the block diagram. Each block produces an outputeither continuously (a continuous block) or at specific points in time(a discrete block).

Other examples of block diagrams include state chart diagrams such asthose found within Stateflow, also available from The MathWorks, Inc,data flow diagrams, and so on. Many graphical programming systemsemploying block diagrams are hierarchical. A hierarchical diagramconsists of ‘layers’ where a layer is a diagram in itself and isrepresent in the ‘parent’ layer as a single block. Connections to theblock are routed into the lower layer.

Thus, there are a variety of different model representations formodeling a dynamic, or other, system, including all of theabove-mentioned text-based and graphically-based modeling techniques, inaddition to other modeling environments, such as Unified ModelingLanguage (UML). UML can be characterized as a general-purpose notationallanguage for specifying and visualizing complex software. The languageis particularly efficient at handling larger, object-oriented, programs.UML is a more recent modeling language that builds on previousnotational methods, such as Booch, OMT, and DOSE. Other modelinglanguages can also fall into the classification of modelrepresentations.

In the field of simulation programs using model representations,including graphical block modeling applications and text-based modelingapplications, there are instances of automated code generators.Automated code generators, in the context of these simulation programs,generally provide automated functionality for the creation of code orfunctions based on a selected configuration with defined parameters. Themore common application of automated code generators is the automatedconversion of a block diagram model to a text-based software algorithm.When automated code generators transform hierarchical block diagramsinto executable functions, the hierarchy of the model maps to thefunctional call graph of the generated code. Users of automated codegenerators often desire control of the function signatures of thefunctions produced by the code generators.

A function signature, as utilized herein, refers to, e.g., data types,domains, and order of inputs and outputs for a function. More generally,a function signature is a collection of information or parameters thatcharacterize how a particular function is invoked, or how a functionproduces a result. In an auto-coding process, a function signature canbe modified to provide some definition as to how automatically generatedfunctions should be structured.

In some instances, necessary arguments to the functions that areautomatically generated are generally not immediately obvious to a user.Typically, many arguments are artifacts resulting from implementing anobject oriented design specification, such as functional units withinternal states, with a procedural language such as C or Ada. Forexample, many arguments do not map directly to the input and outputports of the system or model to which the function corresponds;therefore some of these types of arguments may not be visible to theuser. In addition, it can be cumbersome to maintain a literalspecification of the function signatures as elements of a model areadded or deleted, which changes the exact number and types of functionarguments.

SUMMARY OF THE INVENTION

There is a need for a system and method enabling a user to specifyfunction signatures for automated code generators and optionally previewthe resulting functions, if desired, using a user interface. The presentinvention is directed toward further solutions to address this need.

In accordance with one embodiment of the present invention, in anelectronic device, a method for automatically generating a functionbased on a model representation includes providing at least a portion ofthe model representation. A function signature for the modelrepresentation is received. The function signature is generated by auser. The function is generated based, at least in part, on the modelrepresentation and the function signature.

In accordance with aspects of the present invention, the functionsignature includes at least one of a number of arguments, an order ofarguments, a type of argument return, and a name for the function. Themodel representation includes at least one of a graphical modelrepresentation and a textual model representation. The functionsignature can indicate parameters causing the function generated tooperate in conjunction with selected legacy code. A plurality ofarguments can be grouped within the function signature.

In accordance with further aspects of the present invention, a userinterface is provided that presents preview of the function generated bythe electronic device at least partially based on the function signatureand the model representation. A user can refine the function signatureby reviewing the preview and manipulating the function signature. Thepreview can be displayed substantially contemporaneous with the userentering the function signature.

In accordance with another aspect of the present invention, the functionsignature is at least partially comprised of regular expressions.

In accordance with another embodiment of the present invention, in anelectronic device, a system for automatically generating a functionbased on a model representation is provided. The system includes amechanism providing at least a portion of the model representation. Auser interface enables a user to specify a function signature. Anautomated code generator is provided for generating the function basedon the model representation and the function signature.

In accordance with another embodiment of the present invention, a mediumholding computer executable steps for carrying out a method ofautomatically generating a function based on a model representation isprovided. The method includes the step of providing at least a portionof the model representation. A function signature for the modelrepresentation is received, wherein the function signature is generatedby a user. The function is generated based on the model representationand the function signature.

BRIEF DESCRIPTION OF THE DRAWINGS

The present invention will become better understood with reference tothe following description and accompanying drawings, wherein:

FIG. 1A depicts a conventional dynamic system described with ordinarydifferential equations (ODE);

FIG. 1B depicts a conventional dynamic system described with differenceequations;

FIG. 1C depicts a conventional dynamic system described with algebraicequations;

FIG. 2 depicts conventional components of a basic block diagram;

FIG. 3 depicts the desired behavior of a conventional integrator block;

FIG. 4 is a flow chart of the sequence of steps used to performconventional simulation of the block diagram;

FIG. 5 depicts the conventional replacement of a collection of blocks ina block diagram with an accumulator block;

FIG. 6A depicts a conventional block diagram and its associated directedgraph;

FIG. 6B depicts a conventional linear sorted list generated from thedirected graph of FIG. 6A;

FIG. 7A depicts an abstract example of a conventional block diagrambeing executed;

FIG. 7B depicts an abstract view of the conventional execution methodsinstantiated by the blocks depicted in FIG. 7A;

FIG. 7C depicts a conventional sorted list generated from the datadependencies between blocks of FIG. 7A;

FIG. 8 depicts a conventional multi-rate system;

FIG. 9 depicts the block diagram of FIG. 7A and FIG. 8 with associatedconventional methods added to the blocks;

FIG. 10 is a flowchart of the conventional sequence of steps followed bya single-tasking execution loop;

FIG. 11A depicts the conventional creation of execution lists fromsorted lists in single task mode;

FIG. 11B depicts the conventional execution timing of block diagrams insingle task mode in timelines synchronized and non-synchronized withreal world time;

FIG. 12A depicts the conventional creation of execution lists fromsorted lists in multi-task mode;

FIG. 12B depicts the conventional execution timing of block diagrams inmulti-task mode;

FIG. 13 is a flowchart of the conventional overall sequence of stepstaken by Simulink® in multi-task mode;

FIG. 14 is a flowchart of the conventional sequence of steps followed bya variable-step solver;

FIG. 15 is a diagrammatic illustration of an electronic device forexecuting the method according to one aspect of the present invention;

FIG. 16 is a diagrammatic illustration of a graphical representation ofa model, in accordance with one aspect of the present invention;

FIG. 17 is a representative screen view of a user interface forpracticing the method of the present invention;

FIG. 18 is a flowchart illustrating a function signature specificationmethod, in accordance with one aspect of the present invention;

FIG. 19 is a diagrammatic illustration of a graphical representation ofa model, in accordance with one aspect of the present invention; and

FIG. 20 is a representative screen view of a user interface forpracticing the method of the present invention.

DETAILED DESCRIPTION

An illustrative embodiment of the present invention relates to a systemand method for specifying function signatures for automated codegenerators transforming hierarchical models, whether in graphical ortextual format, into executable functions. For purposes of clarity ofillustration, the following description is directed toward utilizing anautomated code generator to general executable functions based onhierarchical block diagrams, or other graphically based models orsimulations. The example illustrations are based on the Simulink®modeling application provided by The Mathworks, Inc. of Natick, Mass.However, the present invention is not limited to use with Simulink®, orwith graphical modeling programs in general. Instead, the presentinvention has utility in the automated code generation process of anumber of different model formats, including graphical, text-basedmodels, and other forms of model representations, and associatedlanguages.

The illustrative examples also include use of a graphical user interface(GUI) for implementing the system and method of the present invention.The GUI identifies a subsystem or model for which a user can specify afunction signature. The specification of the function signature can beexecuted using regular expressions, which permit parts or the entireuser interface to be specified as broadly or narrowly as desired. TheGUI further provides a real time code preview of the literal functionsignature that results given the specified function signature. However,a user is not required to make use of regular expressions when defininga function signature.

As referred to previously, and as utilized herein below, a functionsignature refers to, e.g., data types, domains, and order of inputs andoutputs for a function. More generally, a function signature is acollection of information or parameters that characterize how aparticular function is invoked, or how a function produces a result. Inan automated coding process, a function signature can be modified toprovide some definition as to how automatically generated functionsshould be structured.

For purposes of the following description, the phrase “regularexpression” should be interpreted in accordance with convention. Morespecifically, a regular expression can be characterized as an algorithmfor matching strings that follow some pattern. Regular expressions areoften in the form of metacharacters, but can also be unique combinationsof normal characters. Metacharacters include, but are not limited to,symbols on a standard keyboard, such as “*”, “$”, “^”, “.”, or “\”. Themetacharacter “*” is generally known to be a wildcard. The metacharacter“$” typically refers to a match for the end of a line of code. Themetacharacter “^” typically refers to a match for the beginning of aline of code. The metacharacter “.” typically refers to a match for anyone character. The metacharacter “\” typically refers to a quotation ofa following character. The above metacharacter definitions may changedepending on the particular programming language. However, the purposeof the metacharacter is to provide a simple symbol that represents apre-defined action within the code. The normal characters can combine,as well, to form actual words or made-up words, but with a pre-definedaction.

The regular expressions are very useful to programmers when authoringnew programs or code. Usage of regular expressions can make the codingprocess more efficient because the tasks performed by the regularexpressions do not have to be re-created at a code level to carry outthe desired tasks.

Automatically generated code can be generated by a number of differentapplications. One example code-generating tool is the Real-TimeWorkshop, which works in conjunction with Simulink® models. Thecode-generating tool (typically upon instruction by the user) translatesa selected portion of the block diagram (or the entire block diagramitself) into code. Such code could be in a number of possible forms. Thecode may be instructions in a high-level software language such as C,C++, Ada, and the like, hardware descriptions of the block diagramportions in a language such as HDL, or custom code formats suitable forinterpretation in some third-party software. Alternatively, the code maybe instructions suitable for a hardware platform such as amicroprocessor, microcontroller, or digital signal processor, etc., aplatform independent assembly that can be re-targeted to otherenvironments, or just-in-time code (instructions) that corresponds tosections of the block diagram for accelerated performance. Suchautomated code generators are known in the art, and understood by one ofordinary skill in the art.

FIGS. 15 through 20, wherein like parts are designated by like referencenumerals throughout, illustrate an example embodiment of a system andmethod for specifying function signatures for automated code generationin accordance with the present invention. Although the present inventionwill be described with reference to the example embodiments illustratedin the figures, it should be understood that many alternative forms canembody the present invention. One of ordinary skill in the art willadditionally appreciate different ways to alter the parameters of theembodiments disclosed in a manner still in keeping with the spirit andscope of the present invention.

FIG. 15 illustrates one example embodiment of an electronic device 500suitable for practicing the illustrative embodiments of the presentinvention. The electronic device 500 is representative of a number ofdifferent technologies, such as personal computers (PCs), laptopcomputers, workstations, personal digital assistants (PDAs), Internetappliances, cellular telephones, and the like. In the illustratedembodiment, the electronic device 500 includes a central processing unit(CPU) 502 and a display device 504. The display device 504 enables theelectronic device 500 to communicate directly with a user through avisual display. The electronic device 500 further includes a keyboard506 and a mouse 508. Other potential input devices not depicted includea stylus, trackball, joystick, touch pad, touch screen, and the like.The electronic device 500 includes primary storage 510 and secondarystorage 512 for storing data and instructions. The storage devices 510and 512 can include such technologies as a floppy drive, hard drive,tape drive, optical drive, read only memory (ROM), random access memory(RAM), and the like. Applications such as browsers, JAVA virtualmachines, and other utilities and applications can be resident on one orboth of the storage devices 510 and 512. The electronic device 500 canalso include a network interface 514 for communicating with one or moreelectronic devices external to the electronic device 500 depicted. Amodem is one form of network interface 514 used for establishing aconnection with an external electronic device or network. The CPU 502has either internally, or externally, attached thereto one or more ofthe aforementioned components. In addition to applications previouslymentioned, modeling applications and automated code generationapplication, such as Simulink® 516 and Real Time Workshop® 518,respectively, can be installed and operated on the electronic device500.

It should be noted that the electronic device 500 is merelyrepresentative of a structure for implementing the present invention.However, one of ordinary skill in the art will understand that thepresent invention is not limited to implementation on only the describeddevice 500. Other implementations can be utilized, including animplementation based partially or entirely in embedded code, where nouser inputs or display devices are necessary. Rather, a processor cancommunicate directly with another processor, or other device.

FIG. 16 is a screen depiction of a graphical user interface (GUI) 610displaying an example graphical model 612. The graphical model 612depicts a dynamic system having a first input 614 (In1) and a secondinput 616 (In2), each input being of type integer in this example. Thefirst input 614 and second input 616 feed to a Sum 618 function. The Sum618 function adds the two input values together and calculates an output620 (Out). The GUI 610 further includes a display of a functionsignature 622, which is a text-based formula system interfacespecification that defines how a function representing the graphicalmodel 612 should be produced. It should be noted that the graphicalmodel 612 and function signature 622 shown are merely representativeexamples of a model and function signature respectively. The presentinvention is not limited to the example illustration.

In combination with the graphical model 612, a function signature can bespecified by the user. The function signature places various input andoutput restrictions on the automatically generated function or functionsrepresenting the graphical model 612. In the present example, the userhas entered the following function signature 622, using regularexpressions:

-   -   01=foo(&i2,i1)

For the example graphical model 612, and function signature 622 above,the following function will result. Again, this is an exampleillustration. The present invention is not limited to the specificfunction that results. The resulting function that represents thegraphical model in the format defined by the function signaturespecification is:

-   -   int32_T foo(int32_T*In2, int32_T In1) {    -   return (In1+(*In2));    -   }

When generating code, Real Time Workshop creates functions correspondingto the units or components of the model, such as subsystems in themodel, and even the model itself. By necessity, the function hasarguments corresponding to data passed to and from, or maintained by,the unit, e.g. the unit's I/O, the states of the unit, parameters of theunit, as well as various other auxiliary variables such as zero-crossingsignals and continuous state derivatives.

Some attributes of the function and its arguments, such as datatype,complexity, and dimension, are provided or implied by the modelrepresentation, and may not be modified without invalidating thesemantics of the model and the corresponding implemented application.Other attributes, such as the order of the arguments, the argumentpassing mechanism (e.g. by value vs. by reference), and the name of thefunction may be arbitrarily computed or specified during the process ofautomatic code generation, without impacting the semantics of thegenerated application. In the absence of any user specification, thislatter set of attributes is automatically computed based on rules thatattempt to enhance readability of the code. However, readability is asubjective characteristic and it is possible that the rules implementedmay not lead to code that any given user feels is optimally readable.

Therefore, in accordance with the present invention, the functionsignature parameters are provided so the user can gain control over thesecond set of attributes named above (e.g., the order of the arguments,the argument passing mechanism such as by value vs. by reference, andthe name of the function) and optimize the readability and ability tointegrate the code according to the user's personal subjective andobjective criteria. If regular expressions are liberally employed, sothat the function signature is loosely constrained, the automatic codegenerator continues to apply many rules to attempt to maximize thereadability of the code, conforming to the constraints implied to theextent that they exist. However, the success of the strategies employedwill be to a degree a subjective opinion. If regularly expressions arescarcely employed, or not used at all, the automatic code generatorgenerates code that more literally conforms to that which the user hasspecified.

As mentioned, the function signature 622 includes some regularexpression language. In order to understand the regular expressions, astandard syntax is required for a particular software application oroperating system. The syntax rules essentially define the actions of themetacharacter and normal character regular expressions. The syntax rulesfor interpreting the function are provided in accordance with oneexample illustrative embodiment of the present invention, and are asfollows:

An “*” packages all data for a model into a single argument (a structurepassed by reference). For this case, the function return type is void.

Pure capital letters (i.e., no numbers) specify that arguments arepassed by structure reference. The legal set is {I, O, P} for inputs,outputs, and parameters, respectively. For example, “I” specifies thatall input ports are packed into a single inputs structure.Lowercase alphanumeric letters specify individual arguments in aspecified order. The legal set is {i<n>, o<n>} for input, and outputs,respectively. For example, “i1” specifies that input port 1 are passedas an individual argument. Parameters can also be referred to usingnamed indexing, such as “p(<name>)”.Pure lowercase letters followed by “*” specify individual arguments inan unspecified (deterministic) order. The legal set is {i*, o*, p*} forinputs, outputs, and parameters, respectively. For example, i* isequivalent to i1, i2, i3, and the like.Lowercase alphanumeric letter combinations followed by “*” are used toexpand bus signals. The legal set is {i<n>*, o<n>*}for inputs andoutputs, respectively. For example, i3* expands the bus signal drivinginput 3 as individual arguments to the function (only the elementsaccessed by the system).By default, individual scalar input and parameter arguments are passedby value. To pass them by reference, an “&” qualifier is used. All otherarguments, e.g. vectors and outputs, are always passed by reference (inwhich case an & is allowed, but redundant).Unspecified and auxiliary data (dwork, states, modes, etc.) for thesystem is left for an application such as Real Time Workshop® (providedby The Mathworks, Inc. of Natick, Mass.) to optimize, as desired, anddoes not appear in the argument list for single-instance code.Unspecified and auxiliary data is appended to the argument list formulti-instance code. Real Time Workshop® generates optimized, portable,and customizable ANSI C code from Simulink® models.Argument names are pulled from the appropriate location in the model, aspossible. For example, the block name of the first import is used in thegenerated code for the “i1” argument.

As previously discussed, a particular metacharacter or combination ofnormal characters can have a different action depending on theparticular environment in which the metacharacter or normal charactersexist. Thus, in accordance with one embodiment of the present invention,the above guidelines, or syntax, provide a structure for the automatedpreparation of functions based on a user defined function signature.However, it should be noted that the present invention is not limited tothe actual correlation between regular expression and resulting actionas described. In other words, for the example embodiment, the “*” symbolhas been defined as packaging all data for a model into a singleargument. However, the “*” could be defined to execute a differentaction. The syntax, once developed for a particular coding language,should remain the same so that programs written in that language do nothave to be re-written to reflect changes in regular expression actions.Thus, the regular expression definition typically does not vary after acoding language has been developed for a particular application (such asSimulink®).

The function signature 622 can be entered in a preview graphical userinterface (preview GUI) 630 provided in accordance with the presentinvention. FIG. 17 shows the preview GUI 630. The preview GUI 630includes a first column 632 into which a user can enter a functionsignature 634 using regular expressions. The preview GUI 630 furtherincludes a second column 636, which displays a resulting function 638based on input from a graphical model (such as the graphical model 612of FIG. 16). The preview GUI 630 is not limited to the particular layoutor design illustrated. The preview GUI 630 has functionalcharacteristics including a location for a user to enter a functionsignature, and a location for a code preview of the functions that wouldresult from the entered function signature. Such displays, as understoodby one of ordinary skill in the art, can be embodied in a number ofdifferent ways, and the present invention preview GUI 630 anticipatessuch different approaches having the same or similar functionality.

In accordance with the present invention, the user can refine functionsautomatically generated to represent the graphical model 612 using thepreview GUI 630. The refining process can be used to create functionsthat properly mesh with legacy code or library code, for example. Inaddition, the efficiency of the functions automatically generated can beimproved through iterative analysis and refinement. FIG. 18 is aflowchart illustrating one example process for the automated generationand subsequent user refinement of functions representing the graphicalmodel 612.

First, a dynamic system is modeled and provided (step 400) in the formof the graphical model 612. Again, the particular graphical model 612illustrated in FIG. 15 is merely exemplary. The preview GUI 630 isinitiated (step 402). The user then enters a function signature 622defining parameters to be followed by the software application whenautomatically generating the functions to represent the graphical model612 (step 404). As the user specifies the function signature 622, thepreview GUI 630 dynamically displays the function or functions thatresult from the automated code generation process (step 406). It shouldbe noted that the preview functions that are displayed by the previewGUI 630 are provided in real time as changes or entries are made to thefunction signature. Thus, the present invention provides a dynamicenvironment in which users can quickly and efficiently propose functionsignatures and see the effect the functions signatures have on theresulting function(s) of the automated code generator.

The preview technology in the preview GUI 630 does not rely ongenerating code for the entire model and then showing only an excerptcorresponding to the unit for which the signature is provided. Thisapproach would be intractable for large models, for which codegeneration time can be excessive, and not real-time. Instead, thepreview GUI 630 offers a representation of the code that will begenerated for the unit of interest, and generates that representationconsidering only the unit of interest rather than the entire model.

The process used to deliver the preview is different from the codegeneration process employed when generating code for the model in thatthe process used to deliver the preview can operate with a set ofinformation that is partial with respect to the information availablewhen generating code for the model. As a result, the preview can employtokens or regular expressions in place of literal identifiers andexpressions. However, the process used to deliver the preview willemploy tokens or regular expressions only to the extent necessary andthe preview is at least as literal as the specification used to definethe function.

The user can review the resulting function(s) for desiredcharacteristics and decide whether to return to, and modify, thefunction signature 622 to change the resulting functions(s) (step 408),thus repeating the process and refining the resulting functions. Therefinement process can recur as often as desired by the user to arriveat a desired resulting function. Once the user is satisfied with thepreviewed resulting functions, the user can finalize the functionsignature and execute the automated code generation (step 410).

As understood by one of ordinary skill in the art, the functionsignature can include different parameters, such as a number ofarguments, an order of arguments, a type of argument return, a name forthe resulting function(s), and other function characteristics. Thefunction signature can provide parameters that require the resultingfunction(s) to correspond to selected legacy code, which is code thathas been previously provided by a source separate or external to theimmediate model or subsystem being modeled, and thus dictates its ownfunction signature requirements to the user. In other words, legacy codemight have specific requirements, such as any of the above parameters,for handling input values and output values of the legacy code. The userhas complete control, using the system and method of the presentinvention, over the automatically generated code to ensure that theresulting functions will mesh properly with the legacy code.

In accordance with the example embodiment, the user is not limited tohaving a single argument within the function signature 622. Instead, theuser can enter a number of different arguments, representing a number ofdifferent parameters for the automated generation of the resultingfunction(s).

Another example implementation of the present invention relates to theautomatic code generation representing a graphical subsystem as shown inFIGS. 19 and 20. FIG. 19 is a screen depiction of the graphical userinterface (GUI) 10 displaying an example graphical model 650. Thegraphical model 650 depicts a dynamic system having a first input 654(In1), a second input 656 (In2), and a third input 658 (In3), each inputbeing of type integer in this example. The first input 654, second input656, and third input 658 feed to a Switch 660 function. The Switch 660function switches between the first input 654 and the second input 656,and leads to an output 662 (Out). Again, the graphical model 650 shownis merely representative of a model. The present invention is notlimited to the example illustration.

In combination with the graphical model 650, a function signature can bespecified by the user. In the present example, the user has entered thefollowing function signature, using regular expressions:

-   -   bar(o1, &i1*, i2,p{threshold}, i3)

For the example graphical model 650, and function signature above, thefollowing function will result. Again, this is an example illustration.The present invention is not limited to the specific function thatresults. The resulting function that represents the graphical model inthe format defined by the function signature specification is:

void bar(BUS_T*Out1_(—)1, int32_T*Out1_(—)2, int32_T*In1_(—)1,int32_T*In1_(—)2, BUS_T*In2, int32_T threshold, int32_T In3) {

-   -   if (In3>threshold) {        -   Out1→a=*In1_(—)1;        -   Out1→b=*In1_(—)2;    -   } else {        -   Out1→a=In2.a;        -   Out1→b=In2.b;    -   }

}

The function signature can be entered in a preview graphical userinterface (preview GUI) 630 provided in accordance with the presentinvention. FIG. 20 shows the preview GUI 630. The preview GUI 630,having the first column 632 into which a user can enter a functionsignature 670 using regular expressions. The preview GUI 630 furtherincludes the second column 636, which displays a resulting function 672based on input from a graphical model (such as the graphical model 650of FIG. 19). The preview GUI 630 is not limited to the particular layoutor design illustrated as understood by one of ordinary skill in the art.

Thus, the present invention relates to a system and method forspecifying function signatures for automated code generatorstransforming hierarchical models, whether in graphical or textualformat, into executable functions. The process of automated codegeneration itself, based on a given model and function signature, iswell understood by those of ordinary skill in the art. The presentinvention provides additional tools, in the form of regular expressionsand a preview GUI, for the user to more easily and efficiently specifythe function signature to be used in code generation. The exampleillustrations are based on the Simulink® modeling application, and RealTime Workshop®, auto-code generator, provided by The Mathworks, Inc. ofNatick, Mass. However, the present invention is not limited to use withthese specific applications. Instead, the present invention has utilityin the automated code generation process of a number of different modelformats.

Numerous modifications and alternative embodiments of the presentinvention will be apparent to those skilled in the art in view of theforegoing description. Accordingly, this description is to be construedas illustrative only and is for the purpose of teaching those skilled inthe art the best mode for carrying out the present invention. Details ofthe structure may vary substantially without departing from the spiritof the invention, and exclusive use of all modifications that comewithin the scope of the appended claims is reserved. It is intended thatthe present invention be limited only to the extent required by theappended claims and the applicable rules of law.

1. In an electronic device, a method for automatically generating afunction based on an executable block diagram model, comprising:providing on a first graphical user interface (GUI) a portion of theexecutable block diagram model, the portion of the executable blockdiagram model including a block representing an elemental dynamicsystem; receiving a function signature for the portion of the executableblock diagram model, the function signature being generated by a user ona preview GUI, wherein the function signature is displayed on thepreview GUI; automatically generating preview code representing thefunction resulting from the user generated function signature and theportion of the executable block diagram model, the generating performedby evaluating the portion of the executable block diagram model, thefunction corresponding to the portion of the executable block diagrammodel; dynamically displaying the preview code of the function alongwith the function signature on the preview GUI; wherein the user canrefine the function signature by manipulating the function signature andrenew the preview code of the function on the preview GUI; andautomatically generating code for the entire executable block diagrammodel after generating the preview code representing the function, thecode for the entire executable block diagram model comprising thepreview code representing the function corresponding to the portion ofthe executable block diagram model and the function signature.
 2. Themethod of claim 1, wherein the function signature includes at least oneof a number of arguments, an order of arguments, a type of argumentreturn, and a name for the function.
 3. The method of claim 1, whereinthe function signature indicates parameters causing the functiongenerated to operate in conjunction with selected legacy code.
 4. Themethod of claim 1, further comprising grouping a plurality of argumentswithin the function signature.
 5. The method of claim 1, wherein thefunction signature is at least partially comprised of regularexpressions.
 6. In an electronic device, a system for automaticallygenerating a function based on an executable block diagram model,comprising: a processor for: providing on a first graphical userinterface a portion of the executable block diagram model, the portionof the executable block diagram including a block representing anelemental dynamic system; providing a preview user interface for a userto generate a function signature for the portion of the executable blockdiagram model wherein the function signature is displayed on the previewuser interface; automatically generating preview code representing thefunction resulting from the user generated function signature and theportion of the executable block diagram model, the generating performedby evaluating the portion of the executable block diagram model, thefunction corresponding to the portion of the executable block diagrammodel; receiving an input to manipulate the function signature; updatingthe preview code of the function according to the input by evaluatingthe portion of the executable block diagram model; dynamicallydisplaying the preview code of the function along with the functionsignature on the preview user interface; and automatically generatingcode for the entire executable block diagram model after generating thepreview code representing the function, the code for the entireexecutable block diagram model comprising the preview code representingthe function corresponding to the portion of the executable blockdiagram model and the function signature.
 7. The system of claim 6,wherein the function signature includes at least one of a number ofarguments, an order of arguments, a type of argument return, and a namefor the function.
 8. The system of claim 6, wherein the functionsignature indicates parameters causing the function generated to operatein conjunction with selected legacy code.
 9. The system of claim 6,wherein the function signature includes a plurality of arguments. 10.The system of claim 6, wherein the function signature is at leastpartially comprised of regular expressions.
 11. A computer storagedevice holding computer executable instructions for automaticallygenerating a function based on an executable block diagram model, theinstructions comprising: one or more instructions for providing on afirst graphical user interface (GUI) a portion of the executable blockdiagram model, the portion of the executable block diagram modelincluding a block representing an elemental dynamic system; one or moreinstructions for receiving a function signature for the portion of theexecutable block diagram model, the function signature being generatedby a user on a preview GUI, wherein the function signature is displayedon the preview GUI; one or more instructions for automaticallygenerating preview code representing the function resulting from theuser generated function signature and the portion of the executableblock diagram model, the generating performed by evaluating the portionof the executable block diagram model corresponding to the functionsignature, the function corresponding to the portion of the executableblock diagram model; one or more instructions for receiving input fromthe user to refine the function signature, refining comprising modifyingthe function signature; one or more instructions for automaticallygenerating a updated preview code of a refined function corresponding tothe refined function signature, the generating performed by evaluatingthe portion of the executable block diagram model corresponding to therefined function signature; one or more instructions for displaying therefined function signature on the preview GUI; one or more instructionsfor dynamically displaying the preview code of the refined functionalong with the refined function signature on the preview GUI; one ormore instructions for receiving input to generate code for the entireexecutable block diagram; and one or more instructions for automaticallygenerating the code for the entire executable block diagram model aftergenerating the preview code of the refined function, the code for theentire executable block diagram model including the refined function.12. The computer storage medium of claim 11, wherein the functionsignature includes at least one of a number of arguments, an order ofarguments, a type of argument return, and a name for the function. 13.The computer storage device of claim 11, wherein the function signatureindicates parameters causing the function generated to operate inconjunction with selected legacy code.
 14. The computer storage deviceof claim 11, further comprising grouping a plurality of arguments withinthe function signature.
 15. The computer storage device of claim 11,wherein the function signature is at least partially comprised ofregular expressions.